<template>
    <div class="pagination">
        <ul>
            <li @click="changePage(currentPage - 1)" :class="{ disabled: currentPage === 1 }">&lt;</li>
            <li
                v-for="(item, index) of pages"
                :key="index"
                :class="{selected: item === currentPage, 'is-omit': item === '...'}"
                @click="changePage(item)"
            >
                {{ item }}
            </li>
            <li @click="changePage(currentPage + 1)" :class="{ disabled: currentPage === totalPages.length }">&gt;</li>
        </ul>
    </div>
</template>

<script>
    export default {
        name: "Pagination",
        props: {
            currentPage: Number, // 当前页码
            totalCount: Number, // 总条数
            pageSize: Number // 每页显示数量
        },
        computed: {
            // 总页数数组
            totalPages() {
                let arr = []

                for (let i = 1; i <= Math.ceil(this.totalCount / this.pageSize); i++) {
                    arr.push(i);
                }

                return arr;
            },

            // 当前需要渲染的页码
            pages() {
                const c = this.currentPage;
                const t = this.totalPages;

                // 当总页数小于等于5页，直接完整渲染出来
                if (t.length <= 5) {
                    return t;
                }

                // 当前页码小于3页，渲染前5页
                if (c < 4) {
                    let arr = t.slice(0, 5)
                    return [...arr, '...', this.totalPages.length]
                }

                // 当前页码处于最后3个时, 渲染总页数数组的最后五个
                if (t.length - c < 3) {
                    let arr = t.slice(-5)
                    return [1, '...', ...arr]
                }

                // 若不满足上述条件，则可以从当前开始，使当前页面一直处于页码组中间位置
                let arr = t.slice(c - 3, c + 2)
                return [1, '...', ...arr, '...', this.totalPages.length]
            }
        },
        methods: {
            changePage(page) {
                if (page < 1 || page > this.totalPages.length) return

                this.$emit('update:currentPage', page)
            }
        }
    }
</script>

<style scoped>
    .pagination {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
    }

    ul {
        display: flex;
    }

    li {
        margin: 0 5px;
        border: 1px solid #929aab;
        border-radius: 5px;
        padding: 5px 10px;
        user-select: none;
        cursor: pointer;
        transition: .3s;
    }

    li.selected {
        background: #929aab;
        color: #fff;
    }

    li.disabled {
        cursor: not-allowed;
        background: #2d2f34;
        border-color: #2d2f34;
    }

    li.is-omit {
        pointer-events: none;
        border: none;
    }
</style>
